package com.oocl.ha.merchant.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.oocl.ha.merchant.exceptionHandler.XHRexception;

public class LoginInterceptor extends HandlerInterceptorAdapter{
	private List<String> excludedUrls;

    public void setExcludedUrls(List<String> excludedUrls) {
        this.excludedUrls = excludedUrls;
    }

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String requestUri = request.getRequestURI();
		String requestType = request.getHeader("X-Requested-With"); 
        for (String url : excludedUrls) {
            if (requestUri.endsWith(url)) {
                return true;
            }
        } 
		HttpSession hs = request.getSession();
		if(hs.getAttribute("mId")!=null){
			return true;
		}
		
        	if (requestType != null&&requestType.equals("XMLHttpRequest")){ //如果是ajax请求响应头会有，x-requested-with 
        		if (hs.getAttribute("mId")==null) { //未登录
	            System.out.println("#############################");
//	            response.sendRedirect(request.getContextPath() + "/merchant/jsp/index");
	            response.sendRedirect(request.getContextPath() + "/merchant/jsp/merchantLogin.jsp");
        		}
        		else{
        			return true;
        		}
        		return false;
        	}   
        	if(hs.getAttribute("mId")==null){
	        response.sendRedirect("merchantLogin");
        	}
		return false;
	} 
}
